<?php

namespace app\service\order;

use app\common\model\Order;

class Recharge
{
    /**
     * 创建充值订单
     * php迷途小书童
     * 2024/2/28 12:15
     * @param $data
     * @param $user
     */
    public function createRechargeOrder($data, $user)
    {
        $orderData = [];
        $orderData['order_type'] = 3;
        $orderData['order_sn'] = get_order_sn('R');
        $orderData['user_id'] = $user['id'];
        $orderData['order_money'] = $data['money'];
        $orderData['payable_money'] = $data['money'];
        $orderData['remark'] = $data['remark'] ?? '';
        $orderData['status'] = 0;

        $order = Order::create($orderData);
        $auto_cancel_unix = 3600;
        // 添加订单自动关闭队列
        \think\facade\Queue::later($auto_cancel_unix, '\app\job\OrderAutoOper@autoClose', ['order' => $order], 'order');
        return $order;
    }

    /**
     * 充值订单回调，给用户加余额
     * php迷途小书童
     * 2024/2/28 12:15
     * @param $data
     * @param $user
     */
    public function rechargeOrderVerify($order){
        //查询是否匹配充值规则
        $rechargeRule = \app\admin\model\user\RechargeRule::where('money', $order['pay_fee'])
            ->where('status', 1)
            ->order('id', 'desc')
            ->find();
        if ($rechargeRule) {
            $rechargeMoney = $rechargeRule['add_money'];
        } else {
            $rechargeMoney = $order['real_money'];
        }
        // 记录日志
        $moneyLogService = new \app\service\user\UserMoneyLog();
        $moneyLogService->changeMoney($order->user_id, 0, $rechargeMoney, 40, '用户充值', $order->order_sn);
        // 记录通知
        $title = "充值消息";
        $content = "您已充值成功，到账".$rechargeMoney."元";
        $custom = json_encode(['type' => 'recharge']);
        \app\admin\model\operation\OperationSystemMessage::add($order, $title, $content, '', $custom, 10);
    }
}
